import {defineStore} from "pinia";
import {type} from "../model/type";
import {sys} from "../model/system";
import Axios from "../plugins/axios";
import router from "../route";


export const useRouterStore = defineStore('router', {
    state: () => {
        return {
            // 定义 状态数据
            cache: JSON.parse(sessionStorage.getItem('route_cache') as string) as type.RouterCache[] || [] as type.RouterCache[],
            menu_route: MenuToolRoute() as  Promise<sys.Empty[]>
        }
    },
    actions: {
        AddRouteCache(value: type.RouterCache) {
            let index = -1
            // 缓存中存在数据 则跳过
            index = this.cache.findIndex(item => {
                return item.obj.path === value.obj.path
            })
            if (index !== -1) {
                return
            }
            this.cache.push(value)
            // 缓存
            sessionStorage.setItem("route_cache", JSON.stringify(this.cache))
        },
    }
})


export async function  MenuToolRoute():Promise<sys.Empty[]> {
    // 查询数据库菜单标
    let r=await getMenuRoute()
    return r
}

function getMenuRoute() {
    return new Promise<sys.Empty[]>(resolve => {
        Axios.get('/public/menu',{
            params:{
                pid:0
            }
        }).then(response=>{
            let data:sys.Result<sys.Empty[]> =response.data
            if (data.code==='0000'){
                resolve(data.data)
            }
        }).catch(error=>{
            resolve([])
        })
    })
}